//
//  TCSearchViewController.m
//  陶瓷
//
//  Created by 郭天龙 on 15/7/28.
//  Copyright (c) 2015年 王戈. All rights reserved.
//

#import "TCSearchViewController.h"
#import "TCNetworkTool.h"
#import "CompanyModel.h"
#import "TCGuidangTool.h"
#import "CompanyDisplayViewController.h"

#define SEARCHFILENAME @"searchHistoryFile.plist"
#define CLEARBUTTON @"clearHistory"

@interface TCSearchViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>

@property (nonatomic, weak) IBOutlet UITableView *tableview;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, weak) IBOutlet UISearchBar *searchBar;


@end

@implementation TCSearchViewController

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.searchBar resignFirstResponder];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if ([searchBar.text length] == 0) {
        [self.dataArray removeAllObjects];
        [self.dataArray addObjectsFromArray:[self findGuidangHistory]];
        [self.tableview reloadData];
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self saveGuidangHistory:searchBar.text];
    TCNetworkTool *tool = [TCNetworkTool sharedNetTool];
    [tool CompanyListWithBrand:searchBar.text andPN:@"1" andSuccessBlocks:^(NSArray *resultArray) {
        if ([resultArray count] == 0) {
            [self.dataArray removeAllObjects];
            [self.dataArray addObject:@"未找到搜索结果，请输入其它信息!"];
            [self.tableview reloadData];
        }
        else
        {
            [self.dataArray removeAllObjects];
            [self.dataArray addObjectsFromArray:resultArray];
            [self.tableview reloadData];
        }
    } andFailureBlocks:^(NSString *failureMessage) {
        [STAlertView st_promptAlertWithMessage:@"获取数据失败 ,请检查网络后重试!"];
    }];
    
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchCell"];
    
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"searchCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if ([[self.dataArray objectAtIndex:indexPath.row] isKindOfClass:[NSString class]]) {
        if ([[self.dataArray objectAtIndex:indexPath.row] isEqualToString:CLEARBUTTON])
        {
//            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"searchCellD"];
            UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
            [button setTitle:@"清除搜索历史纪录" forState:UIControlStateNormal];
            button.frame = CGRectMake(0, 0, self.tableview.width, 30);
            [button addTarget:self action:@selector(clearGuidangHistory) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:button];
        }
        else
        {
            cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
        }
    }
    else
    {
        CompanyModel *cmodel = [self.dataArray objectAtIndex:indexPath.row];
        UIView *cellview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kDefaultWindowWidth, 60)];
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(10, 6, kDefaultWindowWidth-10, 20)];
        UILabel *detailtitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, kDefaultWindowWidth-10, 20)];
        title.text = cmodel.Brand;
        detailtitle.text = cmodel.Name;
//        cell.textLabel.text = cmodel.Brand;
//        cell.detailTextLabel.text = cmodel.Name;
        title.font = [UIFont boldSystemFontOfSize:16];
        detailtitle.font = [UIFont systemFontOfSize:16];
        detailtitle.textColor = [UIColor lightGrayColor];
        [cellview addSubview:title];
        [cellview addSubview:detailtitle];
        [cell.contentView addSubview:cellview];
        
    }
//    cell.detailTextLabel.textColor = [UIColor lightGrayColor];
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TCNetworkTool *tctool = [TCNetworkTool sharedNetTool];
    if ([[self.dataArray objectAtIndex:0] isKindOfClass:[CompanyModel class]]) {
        CompanyModel *cm = [_dataArray objectAtIndex:indexPath.row];
        [tctool GetCompanyWithID:cm.Id andSuccessBlocks:^(NSArray *resultArray) {
            CompanyDisplayViewController *nextController = [[CompanyDisplayViewController alloc] init];
            self.title = @"";
            nextController.company = resultArray.firstObject;
            [self.navigationController pushViewController:nextController animated:YES];
        } andFailureBlocks:^(NSString *failureMessage) {
            [MBHUDHelper showWarningWithText:failureMessage];
        }];
    }
    else
    {
        self.searchBar.text = [self.dataArray objectAtIndex:indexPath.row];
        [self searchBarSearchButtonClicked:self.searchBar];
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.dataArray = [[NSMutableArray alloc] init];
    self.tableview.tableFooterView = [UIView new];
    
    if ([self.tableview respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableview setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([self.tableview respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableview setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    [self.dataArray addObjectsFromArray:[self findGuidangHistory]];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)clearGuidangHistory
{
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString* filename = [[paths objectAtIndex:0] stringByAppendingPathComponent:SEARCHFILENAME];
        //删除归档文件
    NSFileManager *defaultManager = [NSFileManager defaultManager];
    if ([defaultManager isDeletableFileAtPath:filename]) {
        [defaultManager removeItemAtPath:filename error:nil];
    }
    [self.dataArray removeAllObjects];
    [self.tableview reloadData];
}

- (void)saveGuidangHistory:(NSString *)text
{
    NSMutableSet *tempSet = [NSMutableSet setWithArray:[self findGuidangHistory]];
    
    if ([tempSet containsObject:CLEARBUTTON]) {
        [tempSet removeObject:CLEARBUTTON];
    }
    
    [tempSet addObject:text];
    
    NSArray *tempArr = [tempSet allObjects];
    [TCGuidangTool writeObject:tempArr forFileName:SEARCHFILENAME];
}

- (NSArray *)findGuidangHistory
{
    NSMutableArray *temp = [NSMutableArray arrayWithArray:(NSArray *)[TCGuidangTool objectForFileName:SEARCHFILENAME]];
    if ([temp count] > 0) {
        [temp addObject:[NSString stringWithFormat:@"%@",CLEARBUTTON]];
    }
    return temp;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationItem setTitle:@""];
}

- (IBAction)backAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


@end
